/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.proyectofinal.ramas.service;

import com.proyectofinal.ramas.domain.Company;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author nicolas
 */
@Service("companyService")
@Transactional
public class CompanyService {

	protected static Logger logger = Logger.getLogger("service");
	
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	
	/**
	 * Retrieves all companys
	 * 
	 * @return a list of companys
	 */
	public List<Company> getAll() {
		logger.debug("Retrieving all companys");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Create a Hibernate query (HQL)
		Query query = session.createQuery("FROM  Company");
		
		// Retrieve all
		return  query.list();
	}
	
	/**
	 * Retrieves a single company
	 */
	public Company get( Integer companyID ) {
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing company first
		Company company = (Company) session.get(Company.class, companyID);
		
		return company;
	}
	/**
	 * Adds a new company
	 */
	public void add(Company company) {
		logger.debug("Adding new company");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Save
		session.save(company);
	}
	
	/**
	 * Deletes an existing company
	 * @param companyID the id of the existing company
	 */
	public void delete(Integer companyID) {
		logger.debug("Deleting existing person");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing company first
		Company company = (Company) session.get(Company.class, companyID);
		
		// Delete 
		session.delete(company);
	}
	
	/**
	 * Edits an existing company
	 */
	public void edit(Company company) {
		logger.debug("Editing existing company");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing company via companyID
		Company existingCompany = (Company) session.get(Company.class, company.getCompanyID());
		
		// Assign updated values to this company
		existingCompany.setName(company.getName());

		// Save updates
		session.save(existingCompany);
	}
}

